const fs = require('fs');

function write(onelog, applyName) {
    onelog = onelog + ' \r\n';
    let path = "./log/" + applyName + "/";
    fs.mkdir(path, {recursive: true}, function (err) {
        if (!err) {
            fs.writeFile(
                path + getTime(null, true) + ".log",
                onelog,
                {flag: 'a'},
                err => {
                }
            );
        }
    });
}

/*时间戳格式化（2020-06-10 20:30:02:623）*/
function getTime(t, date = false) {
    let newdate = t && new Date(t) || new Date();
    let y = newdate.getFullYear(),
        m = newdate.getMonth() + 1,
        d = newdate.getDate();

    if (date) {
        return '' + y + (m < 10 && ('0' + m) || m) + (d < 10 && ('0' + d) || d)
    }

    let h = newdate.getHours(),
        min = newdate.getMinutes(),
        s = newdate.getSeconds(),
        ms = newdate.getMilliseconds();
    let tArray = [m, d, h, min, s].map(
        item => (item < 10 && ('0' + item) || item)
    );
    let timestr = `${r"${y}"}-${r"${tArray[0]}"}-${r"${tArray[1]}"} ${r"${tArray[2]}"}:${r"${tArray[3]}"}:${r"${tArray[4]}"}:${r"${ms}"}`;
    return timestr;
}

module.exports = {write, getTime}